package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: baiml
 * @Title: AbstractRuleProvider
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/8/16 11:43
 */
public abstract class AbstractRuleProvider<S, P> implements DynamicRuleProvider<List<P>> {

    @Autowired
    private ConfigService configService;

    protected abstract String getRulePostFix(String appName);

    protected  abstract Class<S> getDestType();

    protected  abstract P toRule(String appName, String ip, Integer port, S s);


    @Override
    public List<P> getRules(String appName, String ip, Integer port) throws Exception {

        // 从Nacos配置中心拉取配置
        String rules = configService.getConfig(getRulePostFix(appName),
                NacosConfigUtil.GROUP_ID, NacosConfigUtil.PULL_CONFIG_TIME_OUT);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        List<S> list = JSON.parseArray(rules, getDestType());
        return list.stream().map(i -> toRule(appName, ip, port, i)).collect(Collectors.toList());
    }
}
